//引入所有接口参数
import { getData, addNodeApi, updateNodeApi, delNodeApi, addEdgesApi, updateEdgesApi, delEdgesApi } from '../api/index'
import { DataSet, Network } from 'vis/index-network'
import '../index.css'// 直接 导出css 而不是再用js里的插入css的方式了
import '../vis-network.min.css'
const uuidv4 = require('uuid/v4');
//从app得到的play_id
// var nodeData = [];//原始数据
// var edgesData = [];
var nodesDataSet = null;//原始数据转vis数据
var edgesDataSet = null;
var isDgaValue = false; //无环
var newNodeData = null;//编辑时新添加的视频数据
var container = document.getElementById('mynetwork');
window.network = null; //画板对象

(function (doc, win) {
    var docEl = doc.documentElement,
        resizeEvt = "orientationchange" in window ? "orientationchange" : "resize",
        recalc = function () {
            var clientWidth = docEl.clientWidth;
            if (!clientWidth) return;
            if (clientWidth >= 750) {
                docEl.style.fontSize = "100px";
            } else {
                docEl.style.fontSize = 100 * (clientWidth / 750) + "px";
            }
        };

    if (!doc.addEventListener) return;
    recalc();
    win.addEventListener(resizeEvt, recalc, false);
})(document, window);

var manipulation = {
    initiallyActive: true,
    addNode: function (data, callback) {
        callback(newNodeData)
        newNodeData.forEach(item => {
            item.label = item.label.split('\n\n')[1]
        })
        addNodeApi({ nodeData: newNodeData })
    },
    addEdge: function (data, callback) {
        if (data.from == data.to) {
            showAlert("请不要进行连接自身节点的操作");
        } else {
            editEdgeWithoutDrag(data, callback);
        }
    },
    editEdge: {
        editWithoutDrag: function (data, callback) {
            data.type = "Edit"
            editEdgeWithoutDrag(data, callback);
        }
    },
    deleteNode: function (data, callback) {
        delData(data, callback)
    },
    deleteEdge: function (data, callback) {
        delEdge(data, callback)
    }

}
//国际化数据
var locales = {
    cn: {
        edit: '&nbsp',
        del: '&nbsp',
        back: '取消',
        addNode: '&nbsp',
        addEdge: '&nbsp',
        editNode: '&nbsp',
        editEdge: '&nbsp',
        addDescription: '请单击空白区域放置新增加的节点',
        edgeDescription: '单击节点并将边缘拖动到另一个节点以连接它们',
        editEdgeDescription: '单击控制点并将它们拖动到节点以连接到它.'
    }
}
//节点svg 样式 定义
var nodeSvg = '<svg xmlns="http://www.w3.org/2000/svg" width=".32rem" height=".24rem" viewBox="0 0 15.999 12.003">' +
    '  <defs>' +
    '    <style>' +
    '      .cls-1 {' +
    '        fill: #fff;' +
    '      }' +
    '    </style>' +
    '  </defs>' +
    '  <path id="creation_video_selected" class="cls-1" d="M12334.4,4022h-12.8a1.6,1.6,0,0,1-1.6-1.6v-8.8a1.6,1.6,0,0,1,1.6-1.6h12.8a1.6,1.6,0,0,1,1.6,1.6v8.8A1.6,1.6,0,0,1,12334.4,4022Zm-8.343-8.861h0v5.895l4.854-2.947-4.854-2.948Z" transform="translate(-12320.001 -4009.999)"/>' +
    '</svg>';



var url = "data:image/svg+xml;charset=utf-8," + encodeURIComponent(nodeSvg);
var options = {
    manipulation,
    autoResize: false,
    physics: {
        enabled: false,
    },
    edges: {
        arrows: {
            to: {
                enabled: true,
                scaleFactor: 1,
                type: 'arrow'
            },
        },

        font: {
            size: 12
        },
        widthConstraint: {
            maximum: 90
        },

    },
    nodes: {
        shape: 'box',
        borderWidthSelected: 1,
        borderWidth: 1,
        // size: 30,
        widthConstraint: {
            minimum: 60
        },
        shapeProperties: {
            borderRadius: 10,
            // borderDashes: [8, 2],
            // useBorderWithImage: true
        },
        image: url,
        heightConstraint: {
            minimum: 60,
            // valign:top
        },
        color: {
            border: '#888',
            background: '#34374C',
            highlight: {
                border: 'red',//怎么变成虚线
                background: '#34374C',
            }
        },
        font: {
            color: '#fff',
            size: 15, // px
            strokeWidth: 0, // px
            strokeColor: '#ffffff',
            align: 'center',
            multi: false,
            // vadjust: -120
        },
    },

    height: '100%',
    width: '100%',
    locale: 'cn',
    locales: locales,
    clickToUse: true
};
//获取节点的魅力值
function getNodeCount(data) {
    let newdata = localEdgeData.find(item => item.id === data.id)
    if (newdata) data.node_count = newdata.node_count || 0
}
function editEdgeWithoutDrag(data, callback) {
    getNodeCount(data)
    document.getElementById('charmV').value = data.node_count ? data.node_count : 0;
    document.getElementById('edge-operation').value = data.label ? data.label : '';
    document.getElementById('edge-saveButton').onclick = saveEdgeData.bind(this, data, callback);
    document.getElementById('edge-cancelButton').onclick = cancelEdgeEdit.bind(this, callback);
    document.getElementById('edge-popUp').style.display = 'block';
}

function cancelEdgeEdit(callback) {
    clearEdgePopUp();
    callback(null);
}
//保存连线的回调
function saveEdgeData(data, callback) {
    if (typeof data.to === 'object')
        data.to = data.to.id
    if (typeof data.from === 'object')
        data.from = data.from.id
    data.label = document.getElementById('edge-operation').value;
    clearEdgePopUp();
    //如果线重复了不增加( data.type = "Edit")
    if (isRepeat(data) && data.type != "Edit") {
        showAlert("不能添加重复的连线");
        return false;
    } else if (data.label == '' || data.label == null) {
        toast('请填写互动语')
    }
    else {
        callback(data);//先本地增加线
        //排除相反的线或都产生闭环的线
        edgesTool(data, network)
        if (!isDgaValue) {
            isReverse(data);//清除相反的线
        }
    }
}
//消除更改线的弹窗
function clearEdgePopUp() {
    document.getElementById('edge-saveButton').onclick = null;
    document.getElementById('edge-cancelButton').onclick = null;
    document.getElementById('edge-popUp').style.display = 'none';
}

//删除节点
function delData(data, callback) {
    console.log(data)
    showConfirm('确定删除该节点', (c) => {
        if (c) {
            console.log(c)
            var delNodeData = {
                node_id: data.nodes[0]
            }
            delNodeApi(delNodeData)
            callback(data);
        } else {
            callback()
        }
    })
}
//删除关系
function delEdge(data, callback) {
    let options = {
        id: data.edges[0]
    }
    showConfirm('确定删除该关系', (c) => {
        if (c) {
            delEdgesApi(options)
            callback(data);
        } else {
            callback()
        }
    })
}

// 1初始化时增加视频时渲染画板和再编辑剧情时渲染画板
var initDraw = function (data, isinit) {
    //赋值随机id
    if (typeof data == 'string') {
        data = JSON.parse(data)
    }
    for (let index = 0; index < data.nodeData.length; index++) {
        data.nodeData[index].label = data.nodeData[index].batch_id + '.' + data.nodeData[index].batch_num + '\n\n' + data.nodeData[index].label
        if ('node_id' in data.nodeData[index]) {
            data.nodeData[index].id = data.nodeData[index].node_id;
        } else {
            data.nodeData[index].node_id = data.nodeData[index].id = uuidv4();
        }
    }
    var nodeData = data.nodeData;//其他地方要用(本地添加节点，和线时)
    var edgesData = data.edgesData;
    //调用增加点和关系api,只有第一次时

    nodesDataSet = new DataSet(nodeData);
    edgesDataSet = new DataSet(edgesData);
    network = new Network(container, { nodes: nodesDataSet, edges: edgesDataSet }, options);
    if (isinit) {
        nodeData.forEach(item => {
            item.label = item.label.split('\n\n')[1]
        })
        addNodeApi({ nodeData })
    }
    localEdgeData = data.edgesData;//本地保存线的数据,以便修改魅力值
    diyNode();
}
//得到当前network 的 node 数据
var getNowNode = function () {
    let nodeD = network.body.data.nodes._data;
    let nodeData = Object.keys(nodeD).map(item => nodeD[item])
    return nodeData
}
//得到当前network 的 edge 数据
var getNowedge = function () {
    let edgesD = network.body.data.edges._data;
    let edgesData = Object.keys(edgesD).map(item => edgesD[item])
    return edgesData
}
//如果返回true 则是说明有两个以上开头
var getDrawData = function () {
    let nodeData = getNowNode();
    let edgesData = getNowedge();
    return isOneof(nodeData, edgesData);
}

//增加视频
var addVideo = function (data) {
    for (let index = 0; index < data.length; index++) {
        if (typeof data[index] == 'string') {
            data[index] = JSON.parse(data[index])
        }
        if (!('node_id' in data[index])) {
            data[index].node_id = data[index].id = uuidv4();
        }
        data[index].label = data[index].batch_id + '.' + data[index].batch_num + '\n\n' + data[index].label
    }
    newNodeData = data;
    network.addNodeMode()//无ui调用增加节点
}
//edges数据操作(排除重复和相反的线)
let edgesTool = function (data) {
    //let nodeData = getNowNode();
    //let newedges = getNowedge();
    //isDGA(nodeData, newedges)//运行判断是否有闭环函数
    // if (isDgaValue) {
    //     edgesDataSet.remove({ id: data.id })
    // } else {
    let addEdgesApiData = {
        "edgesData": data
    }
    data.node_count = document.getElementById('charmV').value
    addlocalEdgeData(data);//本地存一个魅力值的数据集合,因为框架只能检测到label 的不能检测到其他的
    console.log(data)
    data.type == "Edit" ? updateEdgesApi(data) : addEdgesApi(addEdgesApiData)
    // }
}
//判断线是否相反,不需要返回
var isReverse = function (data) {
    let newedges = getNowedge();
    newedges.forEach(item => {
        //存在一条相反的线时，删除旧的线
        if (item.to == data.from && item.from == data.to) {
            //本地删除
            edgesDataSet.remove({ id: item.id })
            //线上删除
            delEdgesApi({
                "edgesData": {
                    id: item.id
                }
            })
        }
    })
}
//判断线是否重复
var isRepeat = function (nativeEdge) {
    let newedges = getNowedge()
    let repeat = false;//没有重复的线
    newedges.forEach(item => {
        if (item.from == nativeEdge.from && item.to == nativeEdge.to) {
            repeat = true
        }
    })
    return repeat;
}
//对有向无环图判断
var isDGA = function (nodeData, newedges) {
    let isZeroArr = []; //所有节点的是否有入度,为false表示里面该节点有至少一个入度
    if (nodeData.length == 0) {
        console.log('无环图');
        return false
    } else {
        let nodeArr = []; //节点入度为0入栈,便于删除该节点和边
        nodeData.forEach(item => {
            let toIsZero = newedges.every(item2 => item.id != item2.to)
            isZeroArr.push(toIsZero);
            //当某节点入度为0时
            if (toIsZero) {
                nodeArr.push(item);
            }
        })
        //当所有节点都有入度时===形成闭环
        isDgaValue = isZeroArr.every(item => item == false)
        if (isDgaValue) {
            showAlert("不能产生闭环的连线");
            //进行删除edges数据最后一条的操作并重新setData操作
            return false;
        } else {
            nodeArr.forEach(item => {
                //删除入度为0的节点
                nodeData = nodeData.filter(item3 => item.id != item3.id)
                //删除入度为0的节点的边
                newedges = newedges.filter(item3 => item.id != item3.from)
            })
            isDGA(nodeData, newedges)
        }
    }
}
//保证入度为0唯一
var isOneof = function (nodeData, edgesData) {
    var i = 0;
    var oneS = false;
    var rootNode = null;
    nodeData.forEach(item => {
        let toIsZero = edgesData.every(item2 => item.id != item2.to)//所有线都不指向
        console.log(toIsZero)//true 为所有都不指向也就是起始点
        if (toIsZero) {
            i++;
            rootNode = item;
        }
        //当某节点入度为0时
    })
    if (i > 1) {
        oneS = true;
    } else {
        //如果只有一个开头保存开头信息
        rootNode.is_root = 1;
        rootNode.label = rootNode.label.split('\n\n')[1]
        updateNodeApi({ nodeData: [rootNode] });
    }
    return oneS;
}
//弹窗提醒
let alert = new AlertClass();
let confirm = new ConfirmClass();
let toastClass = new ToastClass();
function showAlert(msg) {
    alert.show({
        // title: '提示标题',
        content: msg,
        btnText: '我知道了',
    })
}
function showConfirm(msg, cb) {
    // 这里可以自定义
    confirm.show({
        // title: '提示标题',
        content: msg,
        btns: [{
            callback: function (instance) {
                cb(true);
                instance.close = true;
            }
        }, {
            text: '否',
            callback: function () {
                cb()
            }
        }]
    })
}
function toast(msg) {
    toastClass.show({
        text: msg,
        duration: 1000
    })
}

//魅力值加减
(function charmFun() {
    let minu = document.getElementById('minu');
    let add = document.getElementById('add');
    let charmV = 0;
    minu.addEventListener('touchstart', () => {
        charmV = document.getElementById('charmV').value;
        charmV > 0 ? document.getElementById('charmV').value = --charmV : ''
    })
    add.addEventListener('touchstart', () => {
        charmV = document.getElementById('charmV').value;
        document.getElementById('charmV').value = ++charmV;
    })
})()
//自定义点击节点预览视频操作
var diyNode = function () {
    var lookImg = document.getElementsByClassName('vid-diylook')[0];

    network.on('selectNode', (data) => {
        let nodeD = network.body.data.nodes._data;
        let selectNodeid = data.nodes[0];
        lookImg.style.display = 'block';
        lookImg.setAttribute('attr-videoId', nodeD[selectNodeid].video_id)
    })
    network.on('deselectNode', (data) => {
        lookImg.style.display = 'none';
        lookImg.setAttribute('attr-videoId', '')
    })
    lookImg.addEventListener('touchstart', (e) => {
        e.preventDefault();
        console.log('预览视频')
        var vid = lookImg.getAttribute('attr-videoId')
        var params = {
            video_id: vid
        }
        console.log(vid)
        yuer.playVideo(JSON.stringify(params));
    })
}
//每次修改节点时魅力值本地保存
window.localEdgeData = [];
function addlocalEdgeData(data) {
    let ishas = true;
    for (let index = 0; index < localEdgeData.length; index++) {
        if (localEdgeData[index].id === data.id) {
            ishas = false;
            localEdgeData[index].node_count = data.node_count
        }
    }
    if (ishas) {
        localEdgeData.push(data)
    }
}
// 模拟app选择视频初始化页面
var data1 = {
    nodeData: [
        { label: 'eee', batch_id: 2, batch_num: 1, video_id: "339d09412607475d94243af4795dfd6e", node_id: "f8fefbfb-d87b-4998-a634-a7972eeb69a0" },
        { label: '魅力值', batch_id: 2, batch_num: 1, video_id: "139d09412607475d94243af4795dfd6e", node_id: "18fefbfb-d87b-4998-a634-a7972eeb69a0" },
        { label: 'This node000', batch_id: 2, batch_num: 1, video_id: "85cbccc099024587b08fcf1ab213ad08", node_id: "ab235163-5b09-40bb-b960-caac207a2f0f" },
    ],
    edgesData: [{
        from: 'f8fefbfb-d87b-4998-a634-a7972eeb69a0',
        to: 'ab235163-5b09-40bb-b960-caac207a2f0f',
        node_count: '12',
        label: '有魅力值12',
        cc: '123'
    },
    {
        from: '18fefbfb-d87b-4998-a634-a7972eeb69a0',
        to: 'ab235163-5b09-40bb-b960-caac207a2f0f',
        node_count: '13',
        label: '有魅力值13',
        cc: '123'
    }
    ]
}
var data2 =
    [
        { label: 'This node3333', video_id: '12', batch_id: 2, batch_num: 1, node_id: "f8fefbfb-d87b-4998-a634-a7972eeb69a0" }
        , { label: 'This node4444', video_id: '12414414141', batch_id: 2, batch_num: 1, node_id: "ab235163-5b09-40bb-b960-caac207a2f0f" }
    ]
// getData(initDraw)
// initDraw(data1, true)   //增加节点
// initDraw(data1)
// addVideo(data2)
//模拟保存数据
window.getDrawData = getDrawData;//判断两个以上起点
window.addVideo = addVideo;//增加视频
window.initDraw = initDraw;//app数据渲染
window.savePostion = function () {
    let pos = network.getPositions();
    let nodeData = [];

    for (let iterator in pos) {
        let obj = {}
        obj.node_id = iterator;
        obj.x = pos[iterator].x;
        obj.y = pos[iterator].y;
        nodeData.push(obj)
    }
    updateNodeApi({ nodeData });
}